import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from './entities/user.entity';
import { FindOptionsWhere, Like, Repository } from 'typeorm';
import { UpdateUserDto } from './dto/update.dto';
import { UserRole } from './entities/user-role.entity';
import { ListDto } from './dto/list.dto';
import { RoleManage } from '../system/roleManage/entities/roleManage.entity';
import { GlobalAPI } from 'src/common/typings/global';

@Injectable()
export class UserService {
  @InjectRepository(User)
  private readonly userRepository: Repository<User>;

  @InjectRepository(UserRole)
  private readonly userRoleRepository: Repository<UserRole>;

  async update(updateDto: UpdateUserDto) {
    const isExists = await this.userRepository.findOne({
      where: { id: updateDto.id },
    });
    if (!isExists) {
      return new BadRequestException('用户不存在');
    }
    const { userRoles, password, ...updateData } = updateDto;
    console.log(password);

    if (userRoles) {
      await this.userRoleRepository.delete({
        user: { id: updateDto.id },
      });
      const newRelations = userRoles.map((roleId) => {
        const ur = new UserRole();
        ur.user = { id: updateDto.id } as User;
        ur.role = { id: roleId } as unknown as RoleManage;
        return ur;
      });
      await this.userRoleRepository.save(newRelations);
    }
    return await this.userRepository.update(updateDto.id, updateData);
  }

  async list(listDto: ListDto) {
    const { page, limit, username, ...resetListDto } = listDto;
    const query: FindOptionsWhere<Omit<ListDto, 'page' | 'limit'>> =
      resetListDto;
    if (username) {
      query.username = Like(`%${username}%`);
    }

    const [list, total] = await this.userRepository.findAndCount({
      where: query,
      skip: (page - 1) * limit,
      take: limit,
      relations: ['userRoles', 'userRoles.role'],
      select: {
        id: true,
        username: true,
        email: true,
        createdAt: true,
        updatedAt: true,
      },
    });
    const transformedList = list.map((user) => ({
      ...user,
      userRoles: user.userRoles?.map((ur) => ur.role) || [],
    }));
    return {
      list: transformedList,
      total,
      page,
      limit,
    };
  }

  async getMenu(payload: GlobalAPI.PayloadProps) {
    const { sub } = payload;
    if (!sub) {
      return new BadRequestException('用户不存在');
    }
    const user = await this.userRepository.findOne({
      where: { id: sub },
      relations: ['userRoles', 'userRoles.role', 'userRoles.role.menus'],
    });
    if (!user) {
      return new BadRequestException('用户不存在');
    }
    const menuList = user.userRoles.map((ur) => ur.role.menus).flat();
    return menuList;
  }
}
